#!/usr/bin/python
# -*- coding: utf-8 -*-

import serial, getopt, sys, time

def send_receive(ser,message):
	ser.write(message + '\r\n')
	reply = ''
	
	# give the device a maximum time to reply
	timeout = 3
	
	start_time = time.time()
	while (ser.inWaiting() == 0):
		time.sleep(0.2)
		if time.time() - start_time > 2: 
			break
	
	num_chars = ser.inWaiting()
	
	if num_chars:
		reply += ser.read(num_chars)
		return reply
	else:
		return 'No reply'

def run_interactive(ser):
	input=1
	while 1 :
		# get keyboard input
		input = raw_input(">> ")
			# Python 3 users
			# input = input(">> ")
		if input == 'exit':
			ser.close()
			exit()
		reply = send_receive(ser,input)
		print '\t' + reply

def usage():
	print "\nUsage:\n"
	print "  siw_control.py  -d <serial_device>  [opts] [command]" 
	print " "
	print "    Options:"
	print "      -i --interactive : Talk to serial device through interactive shell"
	print " "
	print "    Commands:"
	print "      -s <message> [--send=<message>]: Send <message> to device"                      
	print "      -t --get-temp                  : Get current board temperature"
	print "      -H <state> [--heater=<state>]  : Set heater to <state> ( '1' for on, '0' for off )"
	print "      -C <state> [--camera=<state>]  : Set camera to <state> ( '1' for on, '0' for off )"
	print "      -S <angle> [--servo=<angle>]   : Turn servo to <angle> ( 10 to 350 degrees in multiples of 2  )"

def main(argv):
	interactive = 0
	get_temp = 0
	turn_servo = 0
	heater_switch = 0
	camera_switch = 0
	send_message = 0
	
	try:                                
		opts, args = getopt.getopt(argv, 'd:itS:H:C:s:', ["help", "device=", "interactive", "get-temp", "turn-servo=","heater=","camera=","send="])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	if not opts:
		usage()
		sys.exit(2)
	for opt, arg in opts:
		if opt in ("--help"):
			usage()                     
			sys.exit()
		elif opt in ("-d", "--device"):
			serial_device = arg             
		elif opt in ("-i", "--interactive"):
			interactive = 1
		elif opt in ("-s", "--send"):
			send_message = 1
			message = arg
		elif opt in ("-t", "--get-temp"):
			get_temp = 1
		elif opt in ("-S", "--turn-servo"):
			turn_servo = 1
			angle = int(arg)
		elif opt in ("-H", "--heater"):
			heater_switch = 1
			heater_state = arg
		elif opt in ("-C", "--camera"):
			camera_switch = 1
			camera_state = arg
			
	# configure the serial connections (the parameters differs on the device you are connecting to)
	ser = serial.Serial(
		port=serial_device,
		baudrate=9600,
		parity=serial.PARITY_ODD,
		stopbits=serial.STOPBITS_TWO,
		bytesize=serial.SEVENBITS
	)
	#!/usr/bin/python
	ser.open()
	ser.isOpen()
	
	if send_message:
		reply = send_receive(ser,message)
		print reply
		sys.exit(0)
		
	if interactive:
		run_interactive(ser)
	
	if get_temp:
		reply = send_receive(ser,'TMP')
		print reply
		sys.exit(0)

	if turn_servo:
		if angle%2 or angle < 10 or angle > 350:
			print "Angle must be a multiple of 2 between 10 and 350"
			sys.exit(1)
		else:
			ascii = angle/2 + 15;
			reply = send_receive(ser,'SRV' + chr(ascii))
			print reply
			sys.exit(0)
	
	if heater_switch:
		reply = send_receive(ser,'HTR' + heater_state)
		print reply
		sys.exit(0)
		
	if camera_switch:
		reply = send_receive(ser,'CAM')
		#if camera_state == '1':
			#reply = send_receive_2(ser,'C')
		#else:
			#reply = send_receive(ser,'C')
		print reply
		sys.exit(0)

main(sys.argv[1:])